package com.gscitysfy.cus.drain.modules.resource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cloudfrmwk.assistant.domain.Result;
import com.gscitysfy.cloudfrmwk.portal.feign.DistrictService;
import com.gscitysfy.cus.drain.config.BusinessException;
import com.gscitysfy.cus.drain.modules.command.entity.DangerSituationManage;
import com.gscitysfy.cus.drain.modules.command.mapper.DangerSituationManageMapper;
import com.gscitysfy.cus.drain.modules.inspection.entity.DrainInspectionMnProblem;
import com.gscitysfy.cus.drain.modules.resource.convert.ResourceCarConvert;
import com.gscitysfy.cus.drain.modules.resource.convert.ResourceWarehouseConvert;
import com.gscitysfy.cus.drain.modules.resource.dto.DrainBaseMnWarehouseDto;
import com.gscitysfy.cus.drain.modules.resource.dto.ResourceCarDto;
import com.gscitysfy.cus.drain.modules.resource.dto.MnWarehouseExcel;
import com.gscitysfy.cus.drain.modules.resource.dto.MnWarehouseRequest;
import com.gscitysfy.cus.drain.modules.resource.dto.ResourceTeamDto;
import com.gscitysfy.cus.drain.modules.resource.entity.DrainBaseChGoods;
import com.gscitysfy.cus.drain.modules.resource.entity.DrainBaseChGoodsResponse;
import com.gscitysfy.cus.drain.modules.resource.entity.DrainBaseMnWarehouse;
import com.gscitysfy.cus.drain.modules.resource.entity.ResourceCar;
import com.gscitysfy.cus.drain.modules.resource.entity.ResourceTeam;
import com.gscitysfy.cus.drain.modules.resource.mapper.DrainBaseChGoodsMapper;
import com.gscitysfy.cus.drain.modules.resource.mapper.DrainBaseMnWarehouseMapper;
import com.gscitysfy.cus.drain.modules.resource.service.IDrainBaseMnWarehouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cus.drain.modules.warning.entity.DrainSignal;
import com.gscitysfy.cus.drain.modules.warning.mapper.DrainSignalMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import com.gscitysfy.cus.drain.utils.HttpResponseUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 物资仓库表 服务实现类
 * </p>
 *
 * @author user
 * @since 2022-10-24 16:57:08
 */
@Service
@AllArgsConstructor
public class DrainBaseMnWarehouseServiceImpl extends ServiceImpl<DrainBaseMnWarehouseMapper, DrainBaseMnWarehouse> implements IDrainBaseMnWarehouseService {

    @Resource
    private DrainBaseMnWarehouseMapper drainBaseMnWarehouseMapper;
    @Resource
    private DrainBaseChGoodsServiceImpl drainBaseChGoodsService;
    @Resource
    private DistrictService districtService;
    @Resource
    private final DangerSituationManageMapper dangerSituationManageMapper;
    private final ResourceWarehouseConvert resourceWarehouseConvert;
    @Override
    public Result<Object> getByPage(Page<DrainBaseMnWarehouse> page, DrainBaseMnWarehouse drainBaseMnWarehouse) {
        IPage<DrainBaseMnWarehouse> drainBaseMnWarehouseList = drainBaseMnWarehouseMapper.getPageList(page, drainBaseMnWarehouse);
        List<DrainBaseMnWarehouse> records = drainBaseMnWarehouseList.getRecords();
        if (records.size() > 0) {
            for (DrainBaseMnWarehouse record : records) {
                QueryWrapper<DrainBaseChGoods> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("warehouse_id", record.getCmKid());
                queryWrapper.eq("cm_usable", false);
                List<DrainBaseChGoods> drainBaseChGoods = drainBaseChGoodsService.list(queryWrapper);
                if (Objects.nonNull(record.getCmRegflag())) {
                    Result<String> result = districtService.getDistrictNameByCode(record.getCmRegflag());
                    if (result.getStatus() == 200) {
                        record.setCmRegflagName(result.getData());
                    }
                }
                record.setBaseChGoodsList(drainBaseChGoods);
            }
        }
        return Result.content(drainBaseMnWarehouseList);
    }
    @Override
    public List<DrainBaseMnWarehouseDto> fetchInIdList(List<Long> idList) {
        LambdaQueryWrapper<DrainBaseMnWarehouse> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(DrainBaseMnWarehouse::getCmKid, idList);
        List<DrainBaseMnWarehouse> drainBaseMnWarehouseList = baseMapper.selectList(queryWrapper);
        return resourceWarehouseConvert.toDtoList(drainBaseMnWarehouseList);
    }
    @Override
    public List<DrainBaseMnWarehouseDto> list(Long dangerSituationId) {
        List<DrainBaseMnWarehouseDto> drainBaseMnWarehouseDtoList = new ArrayList<>();
        if (Objects.isNull(dangerSituationId)) {
            throw new BusinessException("缺少险情管理信息");
        }
        DangerSituationManage dangerSituationManage = dangerSituationManageMapper.selectById(dangerSituationId);
        LambdaQueryWrapper<DrainBaseMnWarehouse> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DrainBaseMnWarehouse::getCmUsable, false);
        List<DrainBaseMnWarehouse> drainBaseMnWarehouseList = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(drainBaseMnWarehouseList)) {
            drainBaseMnWarehouseList.forEach(drainBaseMnWarehouse -> {
                drainBaseMnWarehouseDtoList.add(resourceWarehouseConvert.toDto(drainBaseMnWarehouse, dangerSituationManage));
            });
        }
        return drainBaseMnWarehouseDtoList;
    }

/*    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Boolean saveDrainBaseMnWarehouse(DrainBaseMnWarehouse drainBaseMnWarehouse) {
        boolean b = true;
        completeGeom(drainBaseMnWarehouse);
        b = this.saveOrUpdate(drainBaseMnWarehouse);
        QueryWrapper<DrainBaseChGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("warehouse_id", drainBaseMnWarehouse.getCmKid());
        queryWrapper.eq("cm_usable", false);
        List<DrainBaseChGoods> drainBaseChGoods = drainBaseChGoodsService.list(queryWrapper);
        if (drainBaseChGoods != null && drainBaseChGoods.size() > 0) {
            for (DrainBaseChGoods drainBaseChGood : drainBaseChGoods) {
                drainBaseChGoodsService.delete(drainBaseChGood.getCmKid());
            }
        }
        List<DrainBaseChGoods> drainBaseChGoodsList = drainBaseMnWarehouse.getBaseChGoodsList();
        if (drainBaseChGoodsList != null && drainBaseChGoodsList.size() > 0) {
            for (DrainBaseChGoods drainBaseChGoods2 : drainBaseChGoodsList) {
                drainBaseChGoods2.setWarehouseId(drainBaseMnWarehouse.getCmKid());
                drainBaseChGoods2.setCmUsable(false);
                boolean b1 = drainBaseChGoodsService.saveOrUpdate(drainBaseChGoods2);
                if (b) {
                    b = b1;
                }
            }
        }

        return b;
    }*/

    /**
     * 基于经纬度生成Geom
     *
     * @param drainBaseMnWarehouse
     * @return
     */
    public DrainBaseMnWarehouse completeGeom(DrainBaseMnWarehouse drainBaseMnWarehouse) {
        BigDecimal lgtd = drainBaseMnWarehouse.getLgtd();
        BigDecimal lttd = drainBaseMnWarehouse.getLttd();
        if (Objects.nonNull(drainBaseMnWarehouse.getLgtd()) && Objects.nonNull(drainBaseMnWarehouse.getLttd())) {
            lgtd = lgtd.setScale(6, RoundingMode.HALF_UP);
            lttd = lttd.setScale(6, RoundingMode.HALF_UP);
            String theGeom = "POINT(" + lgtd + " " + lttd + ")";
            drainBaseMnWarehouse.setCmGeom(theGeom);
        }
        return drainBaseMnWarehouse;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public Result delete(Long id) {
        QueryWrapper<DrainBaseChGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("warehouse_id", id);
        queryWrapper.eq("cm_usable", false);
        List<DrainBaseChGoods> drainBaseChGoods = drainBaseChGoodsService.list(queryWrapper);
        if (drainBaseChGoods.size() > 0) {
            return Result.failure("当前仓库存在物资");
        }
        DrainBaseMnWarehouse drainBaseMnWarehouse = drainBaseMnWarehouseMapper.selectById(id);
        drainBaseMnWarehouse.setCmUsable(true);
        boolean b = this.saveOrUpdate(drainBaseMnWarehouse);
        return b==true?Result.success():Result.failure("删除失败");
    }

    @Override
    public Result<Object> getByPages(Page<DrainBaseMnWarehouse> page, MnWarehouseRequest request) {
        IPage<DrainBaseMnWarehouse> drainBaseMnWarehouseList = drainBaseMnWarehouseMapper.getByPages(page, request);
        List<DrainBaseMnWarehouse> records = drainBaseMnWarehouseList.getRecords();
        for (DrainBaseMnWarehouse record : records) {
            List<DrainBaseChGoodsResponse> baseChGoodsResponseListList = record.getBaseChGoodsResponseListList();
            if (CollectionUtils.isNotEmpty(baseChGoodsResponseListList)) {
                for (DrainBaseChGoodsResponse response : baseChGoodsResponseListList) {
                    String goodsName = response.getGoodsName();
                    if (StringUtils.isNotEmpty(record.getGoodsName())) {
                        record.setGoodsName(record.getGoodsName() + goodsName + "、");
                        ;
                    } else {
                        record.setGoodsName(goodsName + "、");
                        ;
                    }
                }
                if (StringUtils.isNotEmpty(record.getGoodsName())) {
                    record.setGoodsName(record.getGoodsName().substring(0, record.getGoodsName().length() - 1));
                }
            }
            if (Objects.nonNull(record.getCmRegflag())) {
                Result<String> result = districtService.getDistrictNameByCode(record.getCmRegflag());
                Result<String> cmOrgflagresult = districtService.getDistrictNameByCode(record.getCmOrgflag());
                if (result.getStatus() == 200) {
                    record.setCmRegflagName(result.getData());
                }
                if (cmOrgflagresult.getStatus() == 200) {
                    record.setCmOrgflag(cmOrgflagresult.getData());
                }
            }
        }
        return Result.content(drainBaseMnWarehouseList);
    }

    @Override
    public void export(String goodsNameReq, List<String> ids, HttpServletResponse res) {
        List<DrainBaseMnWarehouse> records = drainBaseMnWarehouseMapper.getListByIds(goodsNameReq, ids);
        ArrayList<MnWarehouseExcel> excels = new ArrayList<>();
        for (DrainBaseMnWarehouse record : records) {
            MnWarehouseExcel excel = new MnWarehouseExcel();
            List<DrainBaseChGoodsResponse> baseChGoodsResponseListList = record.getBaseChGoodsResponseListList();
            if (CollectionUtils.isNotEmpty(baseChGoodsResponseListList)) {
                for (DrainBaseChGoodsResponse response : baseChGoodsResponseListList) {
                    String goodsName = response.getGoodsName();
                    if (StringUtils.isNotEmpty(record.getGoodsName())) {
                        record.setGoodsName(record.getGoodsName() + goodsName + "、");
                        ;
                    } else {
                        record.setGoodsName(goodsName + "、");
                        ;
                    }
                }
                if (StringUtils.isNotEmpty(record.getGoodsName())) {
                    record.setGoodsName(record.getGoodsName().substring(0, record.getGoodsName().length() - 1));
                }
            }
            if (Objects.nonNull(record.getCmRegflag())) {
                Result<String> result = districtService.getDistrictNameByCode(record.getCmRegflag());
                Result<String> cmOrgflagresult = districtService.getDistrictNameByCode(record.getCmOrgflag());
                if (result.getStatus() == 200) {
                    record.setCmRegflagName(result.getData());
                }
                if (cmOrgflagresult.getStatus() == 200) {
                    record.setCmOrgflag(cmOrgflagresult.getData());
                }
            }
            BeanUtils.copyProperties(record, excel);
            excels.add(excel);
        }

        String fileName = "仓库信息.xlsx";
        try {
            HttpResponseUtil.setResponseHeaders(res, fileName);
            EasyExcel.write(res.getOutputStream(), MnWarehouseExcel.class)
                    .sheet("仓库信息")
                    .doWrite(() -> excels);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}








